import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

export class Request {
    public static axiosInstance: AxiosInstance;

    public static init() {
        // 创建axios实例
        this.axiosInstance = axios.create({
            // baseURL: 'http://121.36.93.104:8001/',
            baseURL: '/api/',
            timeout: 20000,
            withCredentials: true
        });
        // 初始化拦截器
        this.initInterceptors();
        return axios;
    }


    // 初始化拦截器
    public static initInterceptors() {
        this.axiosInstance.interceptors.request.use(
            (config: AxiosRequestConfig) => {
                return config
            }, this.errorHandler
        );


        // 响应拦截器
        this.axiosInstance.interceptors.response.use(
            // 请求成功
            (response: AxiosResponse) => {
                return Promise.resolve(response.data || response)
            }, this.errorHandler
        )
    }

    // 异常拦截处理器
    public static errorHandler = (error: AxiosError) => {
        return Promise.reject(error)
    }
}